<template>
  <div class="app-container">
    <el-row v-if="optType != 'view'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleSelect"
        >选择
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="borrowlineList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" width="120px" align="center" prop="toolCode" :show-overflow-tooltip="true"/>
      <el-table-column label="名称" width="120px" align="center" prop="toolName" :show-overflow-tooltip="true"/>
      <el-table-column label="型号" align="center" prop="spec" :show-overflow-tooltip="true"/>
      <el-table-column label="品牌" align="center" prop="brand"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_tool_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" v-if="optType != 'view'" width="100px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="optType != 'view'"
            v-hasPermi="['tm:borrowline:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="工器具选择" :visible.sync="openSelect" width="1200px" append-to-body>
      <el-card style="border-radius: 10px">
        <el-form :model="selectQuery" ref="selectQueryForm" size="small" :inline="true" v-show="true"
                 label-width="120px">
          <el-form-item label="编号" prop="toolCode">
            <el-input
              v-model="selectQuery.toolCode"
              placeholder="请输入编号"
              clearable
              @keyup.enter.native="handleSelectList"
            />
          </el-form-item>
          <el-form-item label="名称" prop="toolName">
            <el-input
              v-model="selectQuery.toolName"
              placeholder="请输入名称"
              clearable
              @keyup.enter.native="handleSelectList"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSelectQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetSelectQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <div style="height: 15px"></div>
      <el-card style="border-radius: 10px">
        <el-table border :data="selectList" ref="selectTable" @selection-change="handleSelectionChange" height="500">
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column label="编号" align="center" prop="toolCode"/>
          <el-table-column label="名称" align="center" prop="toolName"/>
          <el-table-column label="型号" align="center" prop="spec"/>
          <el-table-column label="品牌" align="center" prop="brand"/>
          <el-table-column label="类型" align="center" prop="toolTypeName"/>
          <<el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_tool_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        </el-table>
        <pagination
          v-show="selectTotal>0"
          :total="selectTotal"
          :page.sync="selectQuery.pageNum"
          :limit.sync="selectQuery.pageSize"
          @pagination="handleSelectList"
        />
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveBorrowLine">确 定</el-button>
        <el-button @click="selectCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { addTool, delTool, getTool, listTool, updateTool } from "@/api/mes/tm/tool";
import{listLine,getLine,addLine,updateLine,delLine}from "@/api/mes/tm/borrowline";

export default {
  name: "Borrowline",
  dicts: ['mes_tool_status'],
  props: {
    optType: null,
    documentId: null,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工器具表格数据
      borrowlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentId:this.documentId,
        documentCode: null,
        documentName: null,
        toolId: this.toolId,
        toolCode: null,
        toolName: null,
      },
      openSelect: false,
      selectQuery: {
        pageNum: 1,
        pageSize: 10,
        toolCode: null,
        toolName: null,
        status:"STORE",
      },
      selectList: [],
      selectTotal: 0,
      selectedRows: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    documentId: function (newVal, oldVal) {
      if (newVal !== oldVal && newVal !== null) {
        this.queryParams.documentId = newVal;
        this.getList();
      }
    }
  },
  methods: {
    /** 查询工器具列表 */
    getList() {
      this.loading = true;
      listLine(this.queryParams).then(response => {
        this.borrowlineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        documentId:this.documentId,
        documentCode: null,
        documentName: null,
        spec:null,
        brand:null,
        toolTypeId:null,
        toolTypeCode:null,
        toolTypeName:null,
        toolId: null,
        toolCode: null,
        toolName: null,
        status:null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工器具";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getTool(lineId).then(response => {
        debugger;
        this.form = response.data;
        this.open = true;
        this.title = "修改其他出库单行";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs[ "form" ].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateTool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除工器具编号为"' + lineIds + '"的数据项？').then(function () {
        return delLine(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleSelectStock() {
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
    },
    // 多选确定
    async handleSaveBorrowLine() {
      const successList = [];
      const failList = [];
      for (const item of this.selectedRows) {
        this.form.documentId = this.documentId;
        this.form.toolId = item.toolId;
        this.form.toolCode = item.toolCode;
        this.form.toolName = item.toolName;
        this.form.spec = item.spec;
        this.form.brand = item.brand;
        this.form.toolTypeId = item.toolTypeId;
        this.form.toolTypeCode = item.toolTypeCode;
        this.form.toolTypeName = item.toolTypeName;
        this.form.status = item.status;
        try {
          await addLine(this.form)
          successList.push(item);
          this.borrowlineList =successList;
        } catch (error) {
          failList.push(item);
          console.error('新增明细失败',error)
        }
      }
      if (successList.length > 0) {
        this.$modal.msgSuccess(`新增成功 ${successList.length} 条`);
      }

      if (failList.length > 0) {
        this.$modal.msgError(`新增失败 ${failList.length} 条，请查看控制台日志`);
      }
      this.openSelect = false;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/borrowline/export', {
        ...this.queryParams
      }, `issueline_${new Date().getTime()}.xlsx`)
    },
    // 打开选择框
    handleSelect() {
      this.openSelect = true;
      this.handleSelectList();
    },
    // 选择取消
    selectCancel() {
      this.openSelect = false;
    },
    // 条件查询选择框列表
    handleSelectList() {
      listTool(this.selectQuery).then(response => {
        this.selectList = response.rows;
        this.selectTotal = response.total;
      })
    },
    // 搜索按钮操作
    handleSelectQuery() {
      this.selectQuery.pageNum = 1;
      this.handleSelectList();
    },
    // 重置按钮操作
    resetSelectQuery() {
      this.resetForm("selectQueryForm");
      this.handleSelectQuery();
    },
  }
};
</script>
